use adb_client::{ADBDeviceExt, ADBServer, ADBServerDevice, DeviceShort, DeviceState};
use std::net::{Ipv4Addr, SocketAddrV4};

pub fn run_adb() {
    tracing::info!("检测设备状态...");
    let server_ip = Ipv4Addr::new(127, 0, 0, 1);
    let server_port = 5037;
    let mut server = ADBServer::new(SocketAddrV4::new(server_ip, server_port));
    server.track_devices(tracking_devices).unwrap();
}

pub fn tracking_devices(device: DeviceShort) -> adb_client::Result<()> {
    tracing::debug!("检测到设备状态变化: {}:{:?}", device.identifier, device.state);
    match device.state {
        DeviceState::Device => {
            tracing::info!("设备[{}]已就绪", device.identifier);
            let server_ip = Ipv4Addr::new(127, 0, 0, 1);
            let server_port = 5037;
            let mut server = ADBServer::new(SocketAddrV4::new(server_ip, server_port));
            let mut device = server
                .get_device_by_name(device.identifier.as_str())
                .map_err(|e| {
                    tracing::info!("连接设备[{}]失败：{e}", device.identifier);
                    e
                })?;
            tracing::info!("连接设备[{:?}]成功", device.identifier);
            device.reverse_remove_all().map_err(|e| {
                tracing::debug!("清除设备[{:?}]端口映射配置失败：{e}", device.identifier);
                e
            })?;
            tracing::info!("清除设备[{:?}]端口映射配置成功", device.identifier);
            device
                .reverse("tcp:6789".to_string(), "tcp:6789".to_string())
                .map_err(|e| {
                    tracing::debug!("添加设备[{:?}]端口映射配置失败：{e}", device.identifier);
                    e
                })?;
            tracing::info!("添加设备[{:?}]端口映射配置成功", device.identifier);
            // device.shell_command()
            // device.shell_command(&["df", "-h"], &mut std::io::stdout());
        }
        _v => {
            println!("on_device_state_changed: {}:{:?}", device.identifier, _v)
        }
    }
    Ok(())
}
